package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/activity/entity"
)

func CreateRanking(dB *gorm.DB, data *entity.Ranking) {

	if err := dB.Save(&data).Error; err != nil {
		panic(err)
	}
}

//
//func InitRanking(dB *gorm.DB, data *entity.Ranking) entity.Ranking {
//
//
//	if data.Date != date {
//		data.Date = date
//		data.Points = 0
//		data.Get = false
//		data.CreatedAt = time.Now()
//		if err := dB.Save(&data).Error; err != nil {
//			panic(err)
//		}
//	}
//
//	return data
//}

func GetMyRanking(dB *gorm.DB, roleID, activityID, date int32) *entity.Ranking {

	var data = entity.Ranking{RoleID: roleID, ActivityID: activityID}
	if err := dB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		}
		panic(err)
	}

	if data.Date != date {
		return nil
	} else {
		return &data
	}
}

func SaveRanking(dB *gorm.DB, data *entity.Ranking) {

	if err := dB.Save(data).Error; err != nil {
		panic(err)
	}
}

func UpdatePoints(dB *gorm.DB, roleID, activityID int32, points int64) {

	if err := dB.Table(entity.Ranking{}.TableName()).Where("role_id = ? and activity_id = ?", roleID, activityID).
		UpdateColumn("points", gorm.Expr("points + ?", points)).Error; err != nil {
		panic(err)
	}
}
